package com.xiaogao.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaogao.autofill.annotation.FillUserInfo;
import com.xiaogao.common.exception.BusinessException;
import com.xiaogao.sys.mapper.SysDeptMapper;
import com.xiaogao.sys.model.SysDept;
import com.xiaogao.sys.model.SysUser;
import com.xiaogao.sys.request.dept.AddParam;
import com.xiaogao.sys.request.dept.UpdateParam;
import com.xiaogao.sys.response.SysDeptResponse;
import com.xiaogao.sys.service.SysDeptService;
import com.xiaogao.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUserService sysUserService;

    @FillUserInfo
    @Override
    public List<SysDeptResponse> queryList() {
        return sysDeptMapper.querySelective();
    }

    @Override
    public void add(AddParam addParam) {
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(addParam, sysDept);
        sysDeptMapper.insert(sysDept);
    }

    @Override
    public void update(UpdateParam updateParam) {
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(updateParam, sysDept);
        sysDeptMapper.updateById(sysDept);
    }

    @Override
    public void delete(Long id) {
        // 如果存在子部门，不能删除
        LambdaQueryWrapper<SysDept> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(SysDept::getParentId,id);
        Long count = sysDeptMapper.selectCount(countWrapper);
        if(count != null && count > 0){
            throw new BusinessException(500,"存在子部门，不能直接删除！请先删除子部门！");
        }
        // 如果部门关联了用户，部门也不能删除
        LambdaQueryWrapper<SysUser> countUserWrapper = new LambdaQueryWrapper<>();
        countUserWrapper.eq(SysUser::getDeptId,id);
        Long userCount = sysUserService.count(countUserWrapper);
        if(userCount != null && userCount > 0){
            throw new BusinessException(500,"部门存在用户，不能直接删除！请先删除此部门的用户！");
        }
        sysDeptMapper.deleteById(id);
    }
}
